<template>
  <div>
    <el-cascader
      ref="cascaderSelect"
      v-model="deptList"
      :show-all-levels="showAllLevels"
      :options="options"
      :props="{
        emitPath:false,
        value: valueName,
        label: labelName,
        children: children,
        checkStrictly: checkStrictly,
        multiple: multiple
      }"
      :popper-class="popperClass"
      :placeholder="placeholder"
      :disabled="disabled"
      separator="/"
      class="dept-select-container cascader-tags"
      size="small"
      collapse-tags
      clearable
      filterable
    >
      <template slot-scope="{ data }">
        <el-tooltip v-if="data[labelName || 'name'].length > 14" placement="top-start" effect="dark">
          <div slot="content" style="max-width: 150px;">{{ data[labelName || 'name'] }}</div>
          <span class="inline-tag ellipsisOne">{{ data[labelName || 'name'] }}</span>
        </el-tooltip>
        <span v-else>{{ data[labelName || 'name'] }}</span>
      </template>
    </el-cascader>
  </div>
</template>

<script>
// import { cascaderSoft } from '@/utils/tools';
export default {
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  props: {
    value: {
      type: Array | String,
      default: () => {
        return [];
      }
    },
    children: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    valueName: {
      type: String,
      default: 'id'
    },
    labelName: {
      type: String,
      default: 'name'
    },
    linkChildren: { // 点击父节点是否同步勾选其所有子节点
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    options: {
      type: Array,
      default: () => {
        return [];
      }
    },
    multiple: { // 是否多选
      type: Boolean,
      default: true
    },
    checkStrictly: {
      type: Boolean,
      default: true
    },
    showAllLevels: {
      type: Boolean,
      default: false
    },
    popperClass: {
      type: String,
      default: ''
    }
  },
  computed: {
    deptList: {
      get() {
        return this.value;
      },
      set(newVal) {
        this.handelChange(newVal, this.value);
        const panel = this.$refs.cascaderSelect.$refs.panel;
        if ((newVal && newVal.length === 0) || !newVal) {
          panel.checkedValue = []; // 清空选中值
          panel.clearCheckedNodes(); // 清空级联选择器选中状态
          panel.activePath = []; // 清除高亮
          panel.syncActivePath(); // 初始化（只展示一级节点）
        }
        // this.$emit('changeValue', this.value);
      }
    }
  },
  methods: {
    handelChange(newVal, oldVal) {
      /**
       *  判断当前操作时勾选还是取消选中
       */
      const newArr = newVal;
      if (this.linkChildren && newArr) {
        const oldArr = oldVal || [];

        const curSelect = this.getDiff(newArr, oldArr); // 比较差异，获取到的就是当前选中的值
        if (curSelect) {
        /**
         * el-cascader 组件需要保证传进去的数组按照树形的顺序依次排序
         */
          if (newArr.length > 0 && typeof newArr === 'object') {
            const isSelect = newArr.length > oldArr.length;
            const node = this.$refs.cascaderSelect.panel.getNodeByValue(curSelect);
            const children = [];
            this.getTreeChildren(node, children);
            // 两个作用：1、如果是新增则为了原数组去重  2、如果是移除则同步删除子节点
            // newArr = newArr.filter(i => !children.includes(i));
            // 此处不可改变原数组，上面的写法会导致选中底部的内容，panel回滚至首个选中项
            for (let i = newArr.length - 1; i >= 0; i--) {
              if (children.includes(newArr[i])) {
                newArr.splice(i, 1);
              }
            }
            if (isSelect) {
              newArr.splice(newArr.indexOf(curSelect) + 1, 0, ...children); // 把新的数据加入进合适的位置（curSelect 的后面）
            }
            // 组件内部更新选中项
            this.$nextTick(() => {
              this.$refs['cascaderSelect'].panel.syncMultiCheckState();
              this.$refs['cascaderSelect'].computePresentTags();
            });
          }
        }
      }
      this.$emit('changeValue', newArr);
    },
    getDiff(newArr, oldArr) {
      let ans = '';
      if (typeof newArr === 'object' && newArr.length > oldArr.length) {
        ans = newArr.filter(i => !oldArr.includes(i));
      } else if (typeof oldArr === 'object') {
        ans = oldArr.filter(i => !newArr.includes(i));
      }
      return ans && ans.length > 0 ? ans[0] : '';
    },
    getTreeChildren(node, ans) {
      if (node && node.children) {
        for (let i = 0; i < node.children.length; i++) {
          ans.push(node.children[i].data[this.valueName]);
          this.getTreeChildren(node.children[i], ans);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.dept-select-container {
  width: 180px;
  &::v-deep {
    .el-tag.el-tag--info {
      color: #406EFF;
      background-color: #ecf1ff;
    }
    .el-input__inner::-webkit-input-placeholder,
    .el-cascader__search-input::-webkit-input-placeholder{
      color: #666;
      font-size: 14px;
    }
    .el-cascader__tags {
      flex-wrap: nowrap;
    }
  }
}
.cascader-tags {
  &::v-deep {
    .el-tag > span {
      min-width: 20px !important;
      max-width: 37px !important;
    }
    .el-tag.el-tag--info:last-child {
      padding-left: 1px;
      padding-right: 1px;
      margin-left: 4px;
    }
    .el-tag.el-tag--info .el-tag__close {
      right: -2px !important;
      top: 1px !important;
    }
    .el-cascader__search-input {
      min-width: 40px !important;
    }
  }
}
</style>
